#include "HttpMng.h"

HttpMng::HttpMng() {
    //连接http请求和完成信号，信号槽机制保证队列消费
    connect(this, &HttpMng::sig_http_finish, this, &HttpMng::slot_http_finish);
}

HttpMng::~HttpMng() = default;

//发起HTTP请求并接收响应
void HttpMng::PostHttpReq(const QUrl &url, const QJsonObject &json, ReqId req_id, Modules mod) {
    //创建一个HTTP POST请求，并设置请求头和请求体
    const QByteArray data = QJsonDocument(json).toJson();
    //通过url构造请求
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(data.length()));

    //发送请求，并处理响应, 获取自己的智能指针，构造伪闭包并增加智能指针引用计数
    auto self = shared_from_this();
    QNetworkReply *reply = _networkManager.post(request, data);

    connect(reply, &QNetworkReply::finished, [reply,self,req_id,mod]() {
        //处理错误的情况
        if (reply->error() != QNetworkReply::NoError) {
            qDebug() << "error: " << reply->errorString();
            //发送信号通知完成
            emit self->sig_http_finish(req_id, "", ERR_NETWORK, mod);
            reply->deleteLater();
            return;
        }
        //无错误则读回请求
        const QString response = reply->readAll();
        //发送信号通知完成
        emit self->sig_http_finish(req_id, response, SUCCESS, mod);
        reply->deleteLater();
    });
}

void HttpMng::slot_http_finish(const ReqId id, const QString &res, const ErrorCodes err, const Modules mod) {
    if (mod == Modules::REGISTER_MOD) {
        //发送信号通知指定模块http响应结束
        emit sig_reg_mod_finish(id, res, err);
    }
}
